#!/bin/bash

# 检查参数
if [ $# -ne 2 ]; then
    echo "用法: $0 <Kubernetes版本>(1.24.17) <Master节点IP>"
    exit 1
fi

kubeadm reset -f
set -e

# 创建目录并切换到该目录
mkdir -p /opt/k8s && cd /opt/k8s
VERSION=$1
MASTER_IP=$2

# 下载kubeadm配置文件
wget https://gitee.com/michelalive/Deploy-repo/raw/master/KylinLinux/kubernetes/attachment/kubeadm.yml

# 修改配置文件
echo "更新 kubeadm 配置文件..."
sed -i "s|advertiseAddress:.*|advertiseAddress: ${MASTER_IP}|" kubeadm.yml
sed -i "s|kubernetesVersion:.*|kubernetesVersion: ${VERSION}|" kubeadm.yml


# 提取配置信息
localAPIEndpoint_advertiseAddress=$(grep 'advertiseAddress' kubeadm.yml | awk '{print $2}')
localAPIEndpoint_bindPort=6443
nodeRegistration_criSocket=$(grep 'criSocket' kubeadm.yml | awk '{print $2}')
nodeRegistration_name=$(grep 'name' kubeadm.yml | awk '{print $2}')
imageRepository=$(grep 'imageRepository' kubeadm.yml | awk '{print $2}')
kubernetesVersion=$(grep 'kubernetesVersion' kubeadm.yml | awk '{print $2}')
podSubnet=$(grep 'podSubnet' kubeadm.yml | awk '{print $2}')
serviceSubnet=$(grep 'serviceSubnet' kubeadm.yml | awk '{print $2}')

# 输出信息并等待用户确认
echo "以下为Kubernets的初始化信息:"
echo "master节点内网地址: $localAPIEndpoint_advertiseAddress"
echo "api-server服务端口: $localAPIEndpoint_bindPort"
echo "节点注册的CRI套接字: $nodeRegistration_criSocket"
echo "节点注册的名称: $nodeRegistration_name"
echo "镜像仓库: $imageRepository"
echo "Kubernetes版本: $kubernetesVersion"
echo "Pod子网: $podSubnet"
echo "服务子网: $serviceSubnet"
echo ""
read -p "确认以上信息无误吗？输入 'yes' 继续: " confirm

if [ "$confirm" == "yes" ]; then
    # 拉取镜像
    echo "开始拉取 Kubernetes 相关镜像"
    # 列出相关镜像:kubeadm config images list --config kubeadm.yml
    for img in $(kubeadm config images list --config kubeadm.yml); do
        crictl pull $img
    done

    # 初始化kubernetes
    echo "开始进行初始化"
    kubeadm init --config=kubeadm.yml
else
    rm -rf /opt/k8s/kubeadm.yml
    echo "操作已取消。"
fi
